<?php

namespace App\Http\Controllers;

use App\Http\Requests\GoodStoreRequest;
use App\Http\Requests\GoodUpdateRequest;
use App\Models\Goods;
use App\Services\GoodCateService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class GoodController extends Controller
{
    /**
     * 商品管理
     */
    public function index() {
        return view('goods.index');
    }
    /**
     * 商品列表api
     */
    public function list(Request $request) {
        $name = $request->post('params');
        $name = (isset($name) && !empty($name['name'])) ? $name['name'] : null ;
        $limit = empty($request->get('limit')) ? 15 : $request->get('limit');
        $goods = Goods::when($name, function ($query, $name) {
                        return $query->where('name', 'like', '%'.$name.'%');
                    })
                    ->orderByDesc('id')
                    ->paginate($limit);

        return $goods;
    }
    /**
     * 创建商品
     */
    public function create(GoodCateService $goodCateService) {
        $list = $goodCateService->getCateList();
        $data = json_encode(formatGoodCateList($list['data']), JSON_UNESCAPED_SLASHES);
        return view('goods.create', ['data' => $data]);
    }
    /**
     * 图片上传接口
     */
    public function upload(Request $request) {
        $editor = $request->input('editor');
        //获取上传目录
        $fileRoot = config('filesystems.disks.local.root');
        $filePre = Str::afterLast($fileRoot, '/');
        //创建目录
        $dir = $fileRoot.'/images/'.date('Ymd');
        if (!File::isDirectory($dir)) {
            $status = File::makeDirectory($dir, 0777, true, true);
            if (!$status) return $this->toJSON(1004, $dir.'创建目录失败');
        }
        $storePath = 'images/'.date('Ymd');
        $path = $request->file('good-img')->store($storePath);
        if (!$path) {
            return $this->toJSON(1005, '上传失败');
        }
        //返回前端路径
        $returnPath = '/'.$filePre.'/'.$path;
        //wangEditor不生成缩略图直接返回
        if ($editor) {
            return json_encode([
                'errno' => 0,
                'data' => [
                    ['url' => $returnPath, 'alt' => '', 'href' => '']
                ],
            ]);
        }
        //生成缩略图
        if (File::exists($fileRoot.'/'.$path)) {
            $img = Image::make($fileRoot.'/'.$path);
            $img->resize(320, 240);
            $sName = $img->filename.'-m.'.$img->extension;
            $img->save($dir.'/'.$sName);
        }
        return $this->toJSON(0, '', 0, ['src' => $returnPath, 'sSrc' => '/'.$filePre.'/'.$storePath.'/'.$sName]);
    }
    /**
     * 保存商品
     */
    public function store(GoodStoreRequest $request) {
        $para = $request->except('_token', 'good-img');
        $good = new Goods($para);
        $result = $good->save();
        if (!$result) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        return $this->toJSON(200);
    }
    /**
     * 编辑商品
     */
    public function edit(Request $request, GoodCateService $goodCateService) {
        $id = $request->input('id');
        $good = Goods::find($id)->toArray();
        $list = $goodCateService->getCateList();
        $data = json_encode(formatGoodCateList($list['data']), JSON_UNESCAPED_SLASHES);
        $cateList = Cache::get('good_category');
        $cateId = getCateId($good['cate_id'], $cateList);
        return view('goods.edit', ['data' => $data, 'good' => $good, 'cateId' => $cateId]);
    }
    /**
     * 更新商品
     */
    public function update(GoodUpdateRequest $request) {
        $id = $request->get('id');
        $good = Goods::find($id);
        $good->cate_id = $request->input('cate_id');
        $good->name = $request->input('name');
        $good->price = $request->input('price');
        $good->price_agent_one = $request->input('price_agent_one');
        $good->price_agent_two = $request->input('price_agent_two');
        $good->detail = $request->input('detail');
        $good->good_img = $request->input('good_img');
        $good->good_img_small = $request->input('good_img_small');
        $status = $good->save();
        if (!$status) {
            return $this->toJSON(1001, '操作失败，请稍后再试');
        }
        return $this->toJSON(200);
    }
    /**
     * 删除商品
     */
    public function delete(Request $request) {
        $id = $request->get('id');
        $good = Goods::find($id);
        $status = Goods::destroy($id);
        if ($status) {
            $img1 = Str::afterLast($good->good_img, '/uploads/');
            $img2 = Str::afterLast($good->good_img_small, '/uploads/');
            Storage::delete([$img1, $img2]);
        }
        return 200;
    }
}
